package com.glsc.ngateway.opmanage.service.xinyi;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.oaflow.dto.XinYiParamDto;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.log.XinYiLog;
import com.glsc.ngateway.common.base.repo.mysql.opmanagemain.log.XinYiLogRepo;
import com.glsc.ngateway.opmanage.service.feign.GatewayFeignService;
import com.glsc.ngateway.opmanage.utils.SpecificationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Service
@Slf4j
public class XinYiService {

    @Resource
    private XinYiLogRepo xinYiLogRepo;

    @Resource
    private GatewayFeignService gatewayFeignService;


    public Page<XinYiLog> page(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<XinYiLog> page = xinYiLogRepo.findAll(SpecificationUtil.buildSpecification(param, XinYiLog.class), pageable);

        return page;
    }

    /**
     * 重新触发新意指令
     *
     * @param id
     */
    public XinYiLog retry(Long id) {
        Optional<XinYiLog> optional = xinYiLogRepo.findById(id);
        if (!optional.isPresent()) {
            return null;
        }

        XinYiLog yiLog = optional.get();
        Assert.isTrue("N".equals(yiLog.getStatus()), "只有失败状态的指令可以重新触发");

        String ret = gatewayFeignService.callXy(yiLog.getParam());
        JSONObject retObject = JSONObject.parseObject(ret);

        yiLog.setStatus("Y");
        if (StrUtil.isEmpty(ret) || null == retObject || null == retObject.get("code") || !"0".equals(retObject.get("code"))
                || Objects.isNull(retObject.getJSONObject("msg")) || !"0".equals(retObject.getJSONObject("msg").getString("retCode"))
        ) {
            yiLog.setStatus("N");
        }
        xinYiLogRepo.save(yiLog);
        return yiLog;
    }


}
